package com.heye.imheye.util;

import com.heye.imheye.dto.UserInfo;
import com.heye.imheye.entity.User;
import com.heye.imheye.security.MyUserDetails;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public abstract class ContextUtil {

    public static UserInfo getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof UsernamePasswordAuthenticationToken token) {
            MyUserDetails userDetails = (MyUserDetails) token.getPrincipal();
            User user = userDetails.getUser();
            return new UserInfo(user.getId());
        }
        throw new RuntimeException();
    }

    public static Long getUserId() {
        return getUserInfo().id();
    }
}
